package com.hengpeng.msls.service.client.impl;

import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.hengpeng.common.configuration.ConfigProvider;
import com.hengpeng.common.configuration.ConfigProviderFactory;
import com.hengpeng.common.constant.Constant;
import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.QueryResult;
import com.hengpeng.common.persist.entity.AbstractEntity.BoolValue;
import com.hengpeng.common.util.DateTimeUtil;
import com.hengpeng.common.util.MoneyUtil;
import com.hengpeng.common.util.ObjectHelper;
import com.hengpeng.common.util.RSASignatureHelper;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.common.util.Validate;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.constants.RespCodeConstants.CommonCode;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.en.BorrowStatus;
import com.hengpeng.itfinbase.en.RewardRedPacketStatus;
import com.hengpeng.itfinbase.en.RewardUseType;
import com.hengpeng.itfinbase.en.TransType;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.partner.CashRequestMsg;
import com.hengpeng.itfinbase.message.partner.CreditAssignRequest;
import com.hengpeng.itfinbase.message.partner.CreditAssignRequest.BidDetail;
import com.hengpeng.itfinbase.message.partner.CreditAssignRequest.BidDetail.BorrowerDetail;
import com.hengpeng.itfinbase.message.partner.CreditAssignRequest.DivDetail;
import com.hengpeng.itfinbase.message.partner.InvestBorrowerDetail;
import com.hengpeng.itfinbase.message.partner.InvestInfoRequestMsg;
import com.hengpeng.itfinbase.message.partner.PartnerTransType;
import com.hengpeng.itfinbase.message.partner.PayRequestMsg;
import com.hengpeng.itfinbase.message.partner.QueryBalanceRequest;
import com.hengpeng.itfinbase.message.partner.QueryBalanceResponse;
import com.hengpeng.itfinbase.message.userInfo.RealNameAuthRequest;
import com.hengpeng.itfinbase.message.userInfo.SendSMSRequest;
import com.hengpeng.itfinbase.message.userInfo.UserInfoRegisterRequest;
import com.hengpeng.itfinbase.message.userInfo.UserInfoResponse;
import com.hengpeng.itfinbase.message.userInfo.UserLoginRequest;
import com.hengpeng.itfinbase.message.userInfo.UserSetProtectPwdRequest;
import com.hengpeng.itfinbase.message.userInfo.UserUpdatePwdRequest;
import com.hengpeng.itfinbase.persist.Account;
import com.hengpeng.itfinbase.persist.BorrowInfo;
import com.hengpeng.itfinbase.persist.CreditAssign;
import com.hengpeng.itfinbase.persist.CreditAssign.AssignStatus;
import com.hengpeng.itfinbase.persist.InvestInfo;
import com.hengpeng.itfinbase.persist.Partner.PartnerType;
import com.hengpeng.itfinbase.persist.ReceivePlan;
import com.hengpeng.itfinbase.persist.RepaymentPlan;
import com.hengpeng.itfinbase.persist.Reward;
import com.hengpeng.itfinbase.persist.RewardRebate;
import com.hengpeng.itfinbase.persist.RewardRedpacket;
import com.hengpeng.itfinbase.persist.UserBankCard;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfinbase.persist.VerifyCode.VerifyType;
import com.hengpeng.msls.config.ConfigUtil;
import com.hengpeng.msls.config.Configuration;
import com.hengpeng.msls.constants.LSConstants;
import com.hengpeng.msls.constants.SystemConfigUtil;
import com.hengpeng.msls.domain.LoginTryLog;
import com.hengpeng.msls.domain.Token;
import com.hengpeng.msls.port.PortFactory;
import com.hengpeng.msls.port.RemoteService;
import com.hengpeng.msls.port.RemoteTransaction;
import com.hengpeng.msls.port.client.message.AccountLogMessage;
import com.hengpeng.msls.port.client.message.AccountMessage;
import com.hengpeng.msls.port.client.message.BindCardRequest;
import com.hengpeng.msls.port.client.message.BindingBankCardMessage;
import com.hengpeng.msls.port.client.message.BorrowInfoQueryMessage;
import com.hengpeng.msls.port.client.message.ClientVersionInfo;
import com.hengpeng.msls.port.client.message.CreditAssignQueryMessage;
import com.hengpeng.msls.port.client.message.FindPwdMessage;
import com.hengpeng.msls.port.client.message.InvestMessage;
import com.hengpeng.msls.port.client.message.InvestQueryMessage;
import com.hengpeng.msls.port.client.message.LoginMessage;
import com.hengpeng.msls.port.client.message.MemberInfoMessage;
import com.hengpeng.msls.port.client.message.MyBorrowQueryMessage;
import com.hengpeng.msls.port.client.message.MyInviteQueryMessage;
import com.hengpeng.msls.port.client.message.MyRebateQueryMessage;
import com.hengpeng.msls.port.client.message.MyRedPacketQueryMessage;
import com.hengpeng.msls.port.client.message.OpenRequestMsg;
import com.hengpeng.msls.port.client.message.PayRequest;
import com.hengpeng.msls.port.client.message.PrivateMessage;
import com.hengpeng.msls.port.client.message.TransMessage;
import com.hengpeng.msls.port.client.message.UserBankCardMessage;
import com.hengpeng.msls.port.client.message.UserDrawMessage;
import com.hengpeng.msls.port.client.message.UserSetProtectPwdMessage;
import com.hengpeng.msls.port.client.vo.client.AccountTransType;
import com.hengpeng.msls.port.client.vo.client.ClientType;
import com.hengpeng.msls.port.client.vo.client.LoginType;
import com.hengpeng.msls.port.client.vo.client.Passport;
import com.hengpeng.msls.port.client.vo.client.WapTransType;
import com.hengpeng.msls.service.ServiceFactory;
import com.hengpeng.msls.service.userInfo.UserInfoService;
import com.hengpeng.msls.tools.JsonUtils;
import com.hengpeng.msls.util.CommUtil;
import com.hengpeng.msls.util.IdCardUtils;
import com.hengpeng.msls.util.InvestUtils;
import com.hengpeng.msls.util.PageUtil;
import com.hengpeng.msls.vo.activity.RewardRedpacketVo;
import com.hengpeng.msls.vo.assign.CreditAssignVo;
import com.hengpeng.msls.vo.borrow.BorrowInfoVo;
import com.hengpeng.msls.vo.invest.InvestInfoVo;

/**
 * <pre>
 * 远程服务接口实现
 * </pre>
 * 
 * @author linriqing
 * @version 1.0, 2012-3-8
 */
@Service
@RemoteService
@Lazy
public class ClientServiceImpl {
    // 客户端：系统参数配置(版本号)
    public final static String android_Client_Version = "Android_Client_Version";

    // 客户端：系统参数配置(升级说明)
    public final static String android_Client_Summary = "Android_Client_Summary";

    // 客户端：系统参数配置(是否强制性升级)
    public final static String android_Client_IsForceUpdate = "Android_Client_isForceUpdate";

    // 苹果客户端：系统参数配置(版本号)
    public final static String iphone_Client_Version = "Iphone_Client_Version";

    // 苹果客户端：系统参数配置(升级说明)
    public final static String iphone_Client_Summary = "Iphone_Client_Summary";

    // 苹果客户端：系统参数配置(是否强制性升级)
    public final static String iphone_Client_IsForceUpdate = "Iphone_Client_isForceUpdate";

    // 手机客户端启动界面广告图片下载
    public final static Long client_IndexImagesUrl_ArticleGroupId = 200L;

    public static final String[] DAY_OF_WEEK = { "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天" };

    public static final Map<String, Token> clientTokenMap = new HashMap<String, Token>();

    private final static Log logger = LogFactory.getLog(ClientServiceImpl.class);

    private static final Map<String, LoginTryLog> loginTryLogMap = new HashMap<String, LoginTryLog>();

    private static String serverPrivateKey = ConfigProviderFactory.getInstance(Constant.HP_COMMON_PROPERTIES_FILEPATH)
            .getConfigByPrimaryKey("wapserver.privatekey");

    private static final String TRANSACTION_RESPONSE_CODE_4054 = "4054";

    private static final String TRANSACTION_RESPONSE_MESSAGE_4054 = "授权信息过期或失效，请重新登录...";

    @Autowired
    private HttpServletRequest request;

    public final static ConfigProvider<String> cp = ConfigProviderFactory
            .getInstance(Constant.HP_COMMON_PROPERTIES_FILEPATH);

    public String page_return_url = cp.getConfigByPrimaryKey("page.return.url");

    public String service_notify_url = cp.getConfigByPrimaryKey("service.notify.url");

    /**
     * 创建token
     * 
     * @param userName
     * @return
     */
    public static String createToken(String userName, String password) {
        if (clientTokenMap.containsKey(userName)) {
            Token token = clientTokenMap.get(userName);
            // 令牌如果还有8个小时到期，则重新获取，这样用户获取到的令牌至少可以使用8个小时以上
            if (token.getExpireTime() < (System.currentTimeMillis() + (8 * 60 * 1000))) {
                token = new Token(userName, password, System.currentTimeMillis());
                clientTokenMap.put(userName, token);
                return token.getSignature();
            } else {
                return token.getSignature();
            }
        } else {
            Token value = new Token(userName, password, System.currentTimeMillis());
            clientTokenMap.put(userName, value);
            return value.getSignature();
        }
    }

    /**
     * 验证token
     * 
     * @param userName
     * @return
     */
    public static Token getToken(String userName) {
        if (clientTokenMap.containsKey(userName)) {
            Token token = clientTokenMap.get(userName);
            if (token.getExpireTime() < System.currentTimeMillis()) {
                return null;
            } else {
                return token;
            }
        } else {
            return null;
        }
    }

    /**
     * 验证token
     * 
     * @param userName
     * @return
     */
    public static boolean validToken(String userName, String signature) {
        if (clientTokenMap.containsKey(userName)) {
            Token token = clientTokenMap.get(userName);
            if (token.getExpireTime() < System.currentTimeMillis()) {
                return false;
            } else {
                return token.getSignature().equals(signature);
            }
        } else {
            return false;
        }
    }

    @Autowired
    @Qualifier("portFactoryImpl")
    private PortFactory portFactory;

    @Autowired
    private UserInfoService userService;

    @Autowired
    protected ServiceFactory serviceFactory;

    /**
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.CrashReport)
    public TransMessage crashreport(TransMessage transMessage) {
        logger.error("Android crash report：" + ObjectHelper.toJson(transMessage));
        return transMessage;
    }

    /**
     * <pre>
     * 刷新客户端用户信息
     * </pre>
     */
    public void refreshPassport(Passport passport) {
        if (passport != null && passport.getUserName() != null) {
            UserInfo userInfo = serviceFactory.getUserInfoService().getUserInfo(passport.getUserName());
            Account account = serviceFactory.getAccountService().getAccount(userInfo.getId());
            passport.setIsInvestor(userInfo.getIsInvestor());
            passport.setIsBorrower(userInfo.getIsBorrower());
            passport.setUserId(userInfo.getId());
            passport.setTrustAccountId(userInfo.getTrustAccountId());
            passport.setMobile(userInfo.getMobile());
            passport.setRealName(userInfo.getRealName());
            passport.setUserName(userInfo.getUserName());
            passport.setIdCode(userInfo.getCardNumber());
            passport.setBalanceMoney(account.getBaseMoney() - account.getFreezeMoney());
            passport.setBaseMoney(account.getBaseMoney());
            passport.setIsRealNameCheck(userInfo.getIsRealNameCheck());
            passport.setIsQuestionCheck(userInfo.getIsQuestionCheck());
            passport.setIsEmailCheck(userInfo.getIsEmailCheck());
            passport.setQuestionType(userInfo.getQuestionType());
            passport.setAnswer(userInfo.getAnswer());
            passport.setIsMobileCheck(userInfo.getIsMobileCheck());
            passport.setEmail(userInfo.getEmail());
            passport.setIsOpenAccount(userInfo.getIsOpenAccount());
            passport.setRecommendCode(userInfo.getRecommendCode());
            passport.setIsBindCard(userInfo.getIsBindCard());
            if (IdCardUtils.validateCard(userInfo.getCardNumber())) {
                passport.setBirthday(IdCardUtils.getYearByIdCard(userInfo.getCardNumber()) + "-"
                        + IdCardUtils.getMonthByIdCard(userInfo.getCardNumber()) + "-"
                        + IdCardUtils.getDateByIdCard(userInfo.getCardNumber()));
            }
        }
    }

    /**
     * 登录
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.Login)
    public TransMessage login(LoginMessage transMessage) {
        logger.info("Login: " + ObjectHelper.toJson(transMessage));
        try {
            Passport passport = transMessage.getPassport();
            String loginName = transMessage.getLoginName();
            if (LoginType.LOGIN.equals(transMessage.getLoginType())) {
                // 限制登录失败次数，存在则表示之前存在登录失败的尝试
                if (loginTryLogMap.containsKey(loginName)) {
                    LoginTryLog loginTryLog = loginTryLogMap.get(loginName);
                    // 如果错误次数小于100，或者已经过了限制登录的有效期，则进行登录验证
                    if ((loginTryLog.getTime() < 100) || (loginTryLog.getExpireTime() < System.currentTimeMillis())) {
                        try {
                            String encpassword = transMessage.getPassword();
                            String decpassword = RSASignatureHelper.decryptByPrivateKey(encpassword, serverPrivateKey,
                                    "utf-8");
                            UserLoginRequest loginRequest = new UserLoginRequest();
                            loginRequest.setUsername(loginName);
                            loginRequest.setPassword(decpassword);
                            loginRequest.setTransType(TransCodeConstants.MemberTransCode.MEMBER_LOGIN);
                            UserInfoResponse loginResponse = (UserInfoResponse) portFactory.remoteTrans(loginRequest);
                            if (!CommUtil.isEmpty(loginResponse)) {
                                if (CommUtil.isSuccess(loginResponse)) {
                                    // 登录成功，移除登录失败记录对象
                                    loginTryLogMap.remove(loginName);
                                    UserInfo userInfo = loginResponse.getUserInfo();
                                    passport.setToken(createToken(userInfo.getUserName(), decpassword));
                                    // 将username设入passport，否则refreshPassport()方法中无法刷新客户端用户信息
                                    passport.setUserName(userInfo.getUserName());
                                    refreshPassport(passport);
                                    transMessage.setCode(RespCodeConstants.CommonCode.TRANS_SUC);
                                    transMessage.setMessage("成功");
                                } else {
                                    // 登录失败，更新登录失败次数记录+1
                                    loginTryLog.setTime(loginTryLog.getTime() + 1);
                                    loginTryLogMap.put(loginName, loginTryLog);
                                    transMessage.setCode(loginResponse.getRespCode());
                                    transMessage.setMessage(loginResponse.getRespDesc());
                                }
                            } else {
                                transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                                transMessage.setMessage("登录返回空");
                            }
                        } catch (GeneralSecurityException e) {
                            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                            transMessage.setMessage("密码校验失败,失败原因：" + e.getMessage());
                            logger.error(e);
                        }
                    } else {
                        transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                        transMessage.setMessage("登录失败次数超限，请检查用户名和密码是否正确，1个小时后再重新登录");
                    }
                } else {// 没有登录失败尝试记录，则正常登录
                    try {
                        String encpassword = transMessage.getPassword();
                        String decpassword = RSASignatureHelper.decryptByPrivateKey(encpassword, serverPrivateKey,
                                "utf-8");
                        UserLoginRequest loginRequest = new UserLoginRequest();
                        loginRequest.setUsername(loginName);
                        loginRequest.setPassword(decpassword);
                        loginRequest.setTransType(TransCodeConstants.MemberTransCode.MEMBER_LOGIN);
                        UserInfoResponse loginResponse = (UserInfoResponse) portFactory.remoteTrans(loginRequest);
                        if (!CommUtil.isEmpty(loginResponse)) {
                            if (CommUtil.isSuccess(loginResponse)) {
                                UserInfo userInfo = loginResponse.getUserInfo();
                                passport.setToken(createToken(userInfo.getUserName(), decpassword));
                                // 将username设入passport，否则refreshPassport()方法中无法刷新客户端用户信息
                                passport.setUserName(userInfo.getUserName());
                                refreshPassport(passport);
                                transMessage.setCode(RespCodeConstants.CommonCode.TRANS_SUC);
                                transMessage.setMessage("成功");
                            } else {
                                // 登录失败，创建登录失败次数记录+1
                                loginTryLogMap.put(loginName, new LoginTryLog(
                                        System.currentTimeMillis() + 60 * 1000 * 1000, 1, loginName));
                                transMessage.setCode(loginResponse.getRespCode());
                                transMessage.setMessage(loginResponse.getRespDesc());
                            }
                        } else {
                            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                            transMessage.setMessage("登录返回空");
                        }
                    } catch (GeneralSecurityException e) {
                        logger.error("RSA解密用户提交密码异常", e);
                        transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                        transMessage.setMessage("密码校验失败");
                    }
                }
            } else if (LoginType.ALIPAY_LOGIN.equals(transMessage.getLoginType())) {
                // 支付宝登录
            } else {
                transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                transMessage.setMessage("不支持的登录方式");
            }
        } catch (Exception e) {
            transMessage.setMessage(e.getMessage());
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            logger.error(e);
        }
        return transMessage;
    }

    /**
     * 注册
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.Register)
    public TransMessage register(LoginMessage transMessage) {
        logger.info("Register: " + ObjectHelper.toJson(transMessage));
        Passport passport = transMessage.getPassport();
        try {
            if (LoginType.REGISTER.equals(transMessage.getLoginType())) {
                try {
                    String encpassword = transMessage.getPassword();
                    String password = RSASignatureHelper.decryptByPrivateKey(encpassword, serverPrivateKey, "utf-8");

                    UserInfoRegisterRequest regRequest = new UserInfoRegisterRequest();
                    regRequest.setUsername(transMessage.getLoginName());
                    regRequest.setPassword(password);
                    regRequest.setMobile(transMessage.getMobile());
                    regRequest.setRegisterSource(UserInfo.RegisterSource.valueOf(passport.getClientType().toString()));
                    regRequest.setTransType(TransCodeConstants.MemberTransCode.MEMBER_REGISTER);
                    regRequest.setVerifyCode(transMessage.getVerifyCode());
                    // 获取邀请码
                    regRequest.setRecommendCode(transMessage.getRecommendCode());
                    UserInfoResponse regResponse = (UserInfoResponse) portFactory.remoteTrans(regRequest);
                    if (!CommUtil.isEmpty(regResponse) && CommUtil.isSuccess(regResponse)) {
                        refreshPassport(passport);
                        transMessage.setPassport(passport);
                    } else {
                        transMessage.setCode(regResponse.getRespCode());
                        transMessage.setMessage(regResponse.getRespDesc());
                    }
                } catch (GeneralSecurityException e) {
                    transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                    transMessage.setMessage("密码校验失败, 原因：" + e.getMessage());
                    logger.error(e);
                }
            } else {
                transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                transMessage.setMessage("不支持的注册方式");
            }
        } catch (Exception e) {
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            transMessage.setMessage(e.getMessage());
            logger.error(e);
        }
        return transMessage;
    }

    /**
     * <pre>
     * 借款标的信息查询
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.BorrowInfoQuery)
    public BorrowInfoQueryMessage borrowInfoQuery(BorrowInfoQueryMessage transMessage) {
        logger.info("BorrowInfoQuery: " + ObjectHelper.toJson(transMessage));
        int curPage = transMessage.getCurrentPage() != null ? transMessage.getCurrentPage() : 1;
        int psize = transMessage.getPageSize() != null ? transMessage.getPageSize() : 10;
        BorrowStatus[] status = { BorrowStatus.RAISE, BorrowStatus.END, BorrowStatus.LOANING,
                BorrowStatus.REPAYMENTING, BorrowStatus.REPAYMENTED };
        ServiceResult<List<BorrowInfo>> sr = serviceFactory.getBorrowInfoService().queryList(status, null, curPage,
                psize);
        PageUtil pUtil = new PageUtil(psize, sr.getReturnListSize(), curPage);
        transMessage.setBorrowifoList(sr.getReturnValue());
        transMessage.setCurrentPage(pUtil.getCurrentPage());
        transMessage.setTotalCount(pUtil.getTotalCount());
        transMessage.setPageSize(pUtil.getPageSize());
        return transMessage;
    }

    /**
     * <pre>
     * 产品详细
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.BorrowInfoDetail)
    public BorrowInfoQueryMessage borrowInfoDetail(BorrowInfoQueryMessage transMessage) {
        logger.info("BorrowInfoDetail: " + ObjectHelper.toJson(transMessage));
        BorrowInfo borrowInfo = serviceFactory.getBorrowInfoService().getBorrowInfo(transMessage.getBorrowInfoId(),
                null);
        List<InvestInfo> resultInvestInfos = serviceFactory.getInvestInfoService().queryInvestList(
                transMessage.getBorrowInfoId(), null, null);
        List<RepaymentPlan> resultRepaymentPlans = serviceFactory.getRepaymentService().getRepaymentPlans(
                transMessage.getBorrowInfoId(), null, null);
        transMessage.setBorrowInfo(borrowInfo);
        transMessage.setInvestInfoList(resultInvestInfos);
        transMessage.setRepaymentPlanList(resultRepaymentPlans);
        transMessage.setSystemDate(new Date());
        return transMessage;
    }

    /**
     * <pre>
     * 投标
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.Invest)
    public InvestMessage invest(InvestMessage transMessage) {
        logger.info("Invest: " + ObjectHelper.toJson(transMessage));
        BorrowInfo borrowInfo = serviceFactory.getBorrowInfoService().getBorrowInfo(transMessage.getBorrowInfoId(),
                BorrowStatus.RAISE);
        Passport passport = transMessage.getPassport();
        if (passport == null) {
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            transMessage.setMessage("请先登录");
            return transMessage;
        }
        if (borrowInfo == null) {
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            transMessage.setMessage("标的不存在,或标的状态异常");
            return transMessage;
        }
        if (transMessage.getInvestMoney() < (borrowInfo.getMinInvest() / 100)
                || transMessage.getInvestMoney() > (borrowInfo.getMaxInvest() / 100)) {
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            transMessage.setMessage("投标金额不能小于最小投资额,并且不能大于最大投资额");
            return transMessage;
        }
        if ((transMessage.getInvestMoney() * 100 - borrowInfo.getMinInvest()) % borrowInfo.getIncMoney() != 0) {
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            transMessage.setMessage("最小投标为:" + MoneyUtil.convertFenToYuan(borrowInfo.getMinInvest()) + "，增量金额必须为:"
                    + MoneyUtil.convertFenToYuan(borrowInfo.getIncMoney()) + "的整数倍");
            return transMessage;
        }
        if ((borrowInfo.getRaiseMoney() + transMessage.getInvestMoney() * 100) > borrowInfo.getBorrowMoney()) {
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            transMessage.setMessage("投资额度已大于剩余融资额度");
            return transMessage;
        }
        if (passport.getIsInvestor() == BoolValue.NO) {
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            transMessage.setMessage("对不起,您不是投资人角色");
            return transMessage;
        }
        if (passport.getUserId().equals(borrowInfo.getBorrowUserId())) {
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            transMessage.setMessage("对不起,您不能投资自己的借款标!");
            return transMessage;
        }
        try {
            QueryBalanceRequest balanceRequest = new QueryBalanceRequest();
            balanceRequest.setUserId(passport.getUserId());
            balanceRequest.setUsrCustId(passport.getTrustAccountId());
            balanceRequest.setPartnerTransType(PartnerTransType.QueryBalanceBg);
            balanceRequest.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
            QueryBalanceResponse balance = (QueryBalanceResponse) serviceFactory.getProtFactory().remoteTrans(
                    balanceRequest);
            if (CommonCode.TRANS_SUC.equals(balance.getRespCode())) {
                if (transMessage.getInvestMoney().doubleValue() > (Double.parseDouble(balance.getAvlBal().replaceAll(
                        ",", "")))) {
                    transMessage.setMessage("余额不足!");
                    transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                    return transMessage;
                }
            } else {
                transMessage.setMessage("投标失败,原因如下：" + balance.getRespDesc());
                transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                return transMessage;
            }
        } catch (Exception e) {
            transMessage.setMessage("投标失败,原因如下：余额查询失败!具体信息如下:" + e.getMessage());
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            logger.error(e);
            return transMessage;
        }
        /**
         * 红包可用性校验,根据红包对应的奖品类型进行判断
         */
        if (transMessage.getRedPacketId() != null) {
            RewardRedpacket rewardRedpacket = serviceFactory.getPersistService().get(RewardRedpacket.class, transMessage.getRedPacketId());
            Reward reward = serviceFactory.getPersistService().get(Reward.class,rewardRedpacket.getRewardId());
            if (rewardRedpacket.getStatus() != RewardRedPacketStatus.CANUSE) {
                transMessage.setMessage("该红包不可用。");
                transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                return transMessage;
            }
            if (reward.getRewardUseType() == RewardUseType.CASH200) {// 200元起投
                if (transMessage.getInvestMoney() < 200) {
                    transMessage.setMessage("使用该红包最低起投金额为200元");
                    transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                    return transMessage;

                }
            } else if (reward.getRewardUseType() == RewardUseType.MULTIPLE100) {// 100倍起投
                if (transMessage.getInvestMoney() * 100 /rewardRedpacket.getMoney()<100) {
                    transMessage.setMessage("使用该红包最低起投金额为红包面值的100倍");
                    transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                    return transMessage;
                }
            }
            if (rewardRedpacket.getMoney() > transMessage.getInvestMoney() * 100) {
                transMessage.setMessage("红包金额已大于投资金额");
                transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                return transMessage;
            }
        }

        InvestInfoRequestMsg reqMsg = new InvestInfoRequestMsg();
        List<InvestBorrowerDetail> borrowerDetails = new ArrayList<InvestBorrowerDetail>();
        InvestBorrowerDetail borrowerDetail = new InvestBorrowerDetail();
        borrowerDetail.setBorrowerCustId(borrowInfo.getBorrowUserTrustAccountId());
        borrowerDetail.setBorrowerAmt(MoneyUtil.convertFenToYuan(transMessage.getInvestMoney() * 100));
        borrowerDetail.setBorrowerRate(LSConstants.CHAR_ONE);
        borrowerDetail.setProId(borrowInfo.getId().toString());
        borrowerDetails.add(borrowerDetail);
        reqMsg.setBorrowerDetails(JsonUtils.createGson().create().toJson(borrowerDetails));
        reqMsg.setTransAmt(String.valueOf(transMessage.getInvestMoney() * 100));
        reqMsg.setUsrCustId(passport.getTrustAccountId());
        reqMsg.setIsFreeze(LSConstants.CHAR_YES);
        reqMsg.setInvestUserName(passport.getUserName());
        reqMsg.setInvestUserId(passport.getUserId().toString());
        reqMsg.setBorrowInfoId(borrowInfo.getId().toString());
        reqMsg.setBorrowName(borrowInfo.getBorrowName());
        reqMsg.setPartnerTransType(PartnerTransType.InitiativeTender);
        reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
        reqMsg.setBgRetUrl(service_notify_url);
        reqMsg.setRetUrl(page_return_url);
        ResponseMessage response = (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(reqMsg);
        transMessage.setCode(response.getRespCode());
        transMessage.setMessage(response.getRespDesc());
        transMessage.setHtmlString(response.getOrderFormContent());
        return transMessage;
    }

    /**
     * <pre>
     * 我的投资记录
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.MyInvestQuery)
    public InvestQueryMessage myInvestQuery(InvestQueryMessage transMessage) {
        logger.info("MyInvestQuery: " + ObjectHelper.toJson(transMessage));
        int curPage = transMessage.getCurrentPage() != null ? transMessage.getCurrentPage() : 1;
        int psize = transMessage.getPageSize() != null ? transMessage.getPageSize() : 10;
        ServiceResult<List<InvestInfoVo>> myServiceResult = serviceFactory.getInvestInfoService().queryMyInvestAndroidList(
                transMessage.getPassport().getUserId(), transMessage.getInvestStatus(), null, curPage, psize);
        PageUtil pUtil = new PageUtil(psize, myServiceResult.getReturnListSize(), curPage);
        transMessage.setInvestInfoList(myServiceResult.getReturnValue());
        transMessage.setCurrentPage(pUtil.getCurrentPage());
        transMessage.setTotalCount(pUtil.getTotalCount());
        transMessage.setPageSize(pUtil.getPageSize());
        return transMessage;
    }

    /**
     * <pre>
     * 回款计划
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.MyInvestDetail)
    public InvestQueryMessage myInvestDetail(InvestQueryMessage transMessage) {
        logger.info("MyInvestDetail: " + ObjectHelper.toJson(transMessage));
        int curPage = transMessage.getCurrentPage() != null ? transMessage.getCurrentPage() : 1;
        int psize = transMessage.getPageSize() != null ? transMessage.getPageSize() : 10;
        Passport passport = transMessage.getPassport();
        ServiceResult<List<ReceivePlan>> result = serviceFactory.getRepaymentService().getReceivePlansList(transMessage.getBorrowInfoId(),
                passport.getUserId(), null, transMessage.getStatus(),curPage,psize);
        PageUtil pUtil = new PageUtil(psize, result.getReturnListSize(), curPage);
        transMessage.setReceivePlanList(result.getReturnValue());
        transMessage.setCurrentPage(pUtil.getCurrentPage());
        transMessage.setTotalCount(pUtil.getTotalCount());
        transMessage.setPageSize(pUtil.getPageSize());
        return transMessage;
    }

    /**
     * <pre>
     * 我的账户
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.AccountQuery)
    public AccountMessage myAccount(AccountMessage transMessage) {
        logger.info("AccountQuery: " + ObjectHelper.toJson(transMessage));
        Passport passport = transMessage.getPassport();
        refreshPassport(passport);
        Account account = serviceFactory.getAccountService().getAccount(passport.getUserId());
        String nowInterestMoney = serviceFactory.getRepaymentService().getInterestMoney(passport.getUserId(),
                new Date());
        Long rewardRedPackageMoney = serviceFactory.getRedPacketService().countRedPacket(passport.getUserId(),new RewardRedPacketStatus[] {RewardRedPacketStatus.CANUSE});
        transMessage.setAccount(account);
        transMessage.setRewardRedPackageMoney(rewardRedPackageMoney);
        transMessage
                .setNowInterestMoney(StringHelper.isEmpty(nowInterestMoney) ? 0l : Long.parseLong(nowInterestMoney));
        transMessage.setCode(RespCodeConstants.CommonCode.TRANS_SUC);
        transMessage.setMessage(RespCodeConstants.CommonCode.TRANS_SUC_MSG);
        return transMessage;
    }

    /**
     * <pre>
     * 我的融资记录
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.MyBorrowQuery)
    public MyBorrowQueryMessage myBorrowQuery(MyBorrowQueryMessage transMessage) {
        logger.info("MyBorrowQuery: " + ObjectHelper.toJson(transMessage));
        int curPage = transMessage.getCurrentPage() != null ? transMessage.getCurrentPage() : 1;
        int psize = transMessage.getPageSize() != null ? transMessage.getPageSize() : 10;
        int myBorrowInfoNum = 0;
        Long myBorrowInfoMoney = 0l;
        Passport passport = transMessage.getPassport();
        ServiceResult<List<BorrowInfoVo>> myServiceResult = serviceFactory.getBorrowInfoService().queryMyList(
                transMessage.getBorrowStatus(), passport.getUserId(), curPage, psize);
        PageUtil pUtil = new PageUtil(psize, myServiceResult.getReturnListSize(), curPage);
        transMessage.setMyBorrowInfoList(myServiceResult.getReturnValue());
        transMessage.setCurrentPage(pUtil.getCurrentPage());
        transMessage.setTotalCount(pUtil.getTotalCount());
        transMessage.setPageSize(pUtil.getPageSize());

        ServiceResult<List<BorrowInfo>> serviceResult = serviceFactory.getBorrowInfoService().queryList(
                new BorrowStatus[] { BorrowStatus.RAISE, BorrowStatus.REPAYMENTING, BorrowStatus.REPAYMENTED,
                        BorrowStatus.END }, passport.getUserId(), -1, -1);
        if (serviceResult.getReturnValue() != null && serviceResult.getReturnValue().size() > 0) {
            myBorrowInfoNum = serviceResult.getReturnValue().size();
            for (BorrowInfo b : serviceResult.getReturnValue()) {
                myBorrowInfoMoney += b.getRaiseMoney();
            }
        }
        transMessage.setMyBorrowInfoMoney(myBorrowInfoMoney);
        transMessage.setMyBorrowInfoNum(myBorrowInfoNum);
        return transMessage;
    }

    /**
     * <pre>
     * 我的融资记录详情
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.MyBorrowDetail)
    public MyBorrowQueryMessage myBorrowDetail(MyBorrowQueryMessage transMessage) {
        logger.info("MyBorrowDetail: " + ObjectHelper.toJson(transMessage));
        BorrowInfo borrowInfo = serviceFactory.getBorrowInfoService().getBorrowInfo(transMessage.getBorrowInfoId(),
                null);
        List<InvestInfo> resultInvestInfos = serviceFactory.getInvestInfoService().queryInvestList(
                transMessage.getBorrowInfoId(), null, null);
        List<RepaymentPlan> resultRepaymentPlans = serviceFactory.getRepaymentService().getRepaymentPlans(
                transMessage.getBorrowInfoId(), null, null);

        transMessage.setBorrowInfo(borrowInfo);
        transMessage.setInvestInfoList(resultInvestInfos);
        transMessage.setRepaymentPlanList(resultRepaymentPlans);
        return transMessage;
    }

    /**
     * <pre>
     * 债权转让信息
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.CreditAssignQuery)
    public CreditAssignQueryMessage creditAssignQuery(CreditAssignQueryMessage transMessage) {
        logger.info("CreditAssignQuery: " + ObjectHelper.toJson(transMessage));
        AssignStatus[] status = new AssignStatus[] { AssignStatus.PUBLISHED, AssignStatus.ASSIGNING,
                AssignStatus.ASSIGNSUCCESS };
        List<CreditAssign> creditAssigns = serviceFactory.getAssignService().queryList(status);
        transMessage.setIndexAssignList(creditAssigns);
        transMessage.setAssign_fee(ConfigUtil.getParameter("ASSIGN_FEE"));
        transMessage.setAssign_rate(ConfigUtil.getParameter("ASSIGN_RATE"));
        return transMessage;
    }

    /**
     * <pre>
     * 我的可转让的债权信息
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.MyCanAssignQuery)
    public CreditAssignQueryMessage myCanAssignQuery(CreditAssignQueryMessage transMessage) {
        logger.info("MyCanAssignQuery: " + ObjectHelper.toJson(transMessage));
        Passport passport = transMessage.getPassport();
        List<CreditAssignVo> dataList = serviceFactory.getAssignService()
                .queryCanCreditAssignList(passport.getUserId());
        transMessage.setCanAssignList(dataList);
        transMessage.setAssign_fee(ConfigUtil.getParameter("ASSIGN_FEE"));
        transMessage.setAssign_rate(ConfigUtil.getParameter("ASSIGN_RATE"));
        return transMessage;
    }

    /**
     * <pre>
     * 我的转让中的债权
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.MyAssigningQuery)
    public CreditAssignQueryMessage myAssigningQuery(CreditAssignQueryMessage transMessage) {
        logger.info("MyAssigningQuery: " + ObjectHelper.toJson(transMessage));
        Passport passport = transMessage.getPassport();
        List<CreditAssignVo> dataList = serviceFactory.getAssignService().queryAssigningList(passport.getUserId());
        transMessage.setAssigningList(dataList);
        transMessage.setAssign_fee(ConfigUtil.getParameter("ASSIGN_FEE"));
        transMessage.setAssign_rate(ConfigUtil.getParameter("ASSIGN_RATE"));
        return transMessage;
    }

    /**
     * <pre>
     * 我的已转出的债权
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.MyAssignedQuery)
    public CreditAssignQueryMessage myAssignedQuery(CreditAssignQueryMessage transMessage) {
        logger.info("MyAssignedQuery: " + ObjectHelper.toJson(transMessage));
        Passport passport = transMessage.getPassport();
        List<CreditAssign> dataList = (List<CreditAssign>) serviceFactory.getAssignService().queryAssignedList(
                passport.getUserId());
        transMessage.setAssignedList(dataList);
        transMessage.setAssign_fee(ConfigUtil.getParameter("ASSIGN_FEE"));
        transMessage.setAssign_rate(ConfigUtil.getParameter("ASSIGN_RATE"));
        return transMessage;
    }

    /**
     * <pre>
     * 我的已购买的债权
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.MyBuyedAssignQuery)
    public CreditAssignQueryMessage myBuyedAssignQuery(CreditAssignQueryMessage transMessage) {
        logger.info("MyBuyedAssignQuery: " + ObjectHelper.toJson(transMessage));
        Passport passport = transMessage.getPassport();
        List<CreditAssignVo> dataList = serviceFactory.getAssignService().queryBuyedList(passport.getUserId());
        transMessage.setBuyedList(dataList);
        transMessage.setAssign_fee(ConfigUtil.getParameter("ASSIGN_FEE"));
        transMessage.setAssign_rate(ConfigUtil.getParameter("ASSIGN_RATE"));
        return transMessage;
    }

    /**
     * <pre>
     * 发布债权
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.PublishAssign)
    public CreditAssignQueryMessage publishAssign(CreditAssignQueryMessage transMessage) {
        logger.info("PublishAssign: " + ObjectHelper.toJson(transMessage));
        CreditAssignRequest createAssignRequest = new CreditAssignRequest();
        createAssignRequest.setInvestInfoId(transMessage.getInvestInfoId());
        createAssignRequest.setTransType(TransCodeConstants.TradeTransCode.TRADE_CREATEASSIGEN);
        createAssignRequest.setAssign_duration(Integer.parseInt(ConfigUtil.getParameter("ASSIGN_DURATION")));
        ResponseMessage response = serviceFactory.getProtFactory().remoteTrans(createAssignRequest);
        transMessage.setCode(response.getRespCode());
        transMessage.setMessage(response.getRespDesc());
        return transMessage;
    }

    /**
     * <pre>
     * 购买债权
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.BuyAssign)
    public CreditAssignQueryMessage buyAssign(CreditAssignQueryMessage transMessage) {
        logger.info("BuyAssign: " + ObjectHelper.toJson(transMessage));
        Passport passport = transMessage.getPassport();
        /** 获取债权实时信息 */
        CreditAssign creditAssign = serviceFactory.getAssignService().getCurrentAssignInfo(transMessage.getAssignId());
        BorrowInfo borrowInfo = serviceFactory.getProtFactory().getEntityById(creditAssign.getBorrowInfoId(),
                BorrowInfo.class);
        InvestInfo investInfo = serviceFactory.getProtFactory().getEntityById(creditAssign.getInvestInfoId(),
                InvestInfo.class);
        if (passport == null) {
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            transMessage.setMessage("承接失败,原因如下：请先登录");
            return transMessage;
        }
        if (passport.getIsInvestor() == BoolValue.NO) {
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            transMessage.setMessage("承接失败,原因如下：当前用户不是投资人角色");
            return transMessage;
        }
        try {
            /**
             * 校验投资人可用余额是否够用
             */
            QueryBalanceRequest queryBalanceRequest = new QueryBalanceRequest();
            queryBalanceRequest.setPartnerType(PartnerType.FUND);
            queryBalanceRequest.setUsrCustId(passport.getTrustAccountId());
            queryBalanceRequest.setPartnerTransType(PartnerTransType.QueryBalanceBg);
            queryBalanceRequest.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
            QueryBalanceResponse queryBalanceResponse = (QueryBalanceResponse) serviceFactory.getProtFactory()
                    .remoteTrans(queryBalanceRequest);
            if (RespCodeConstants.CommonCode.TRANS_SUC.equals(queryBalanceResponse.getRespCode())) {
                Double needMoney = (creditAssign.getSellMoney() / 100)
                        * (1 - Double.parseDouble(ConfigUtil.getParameter("ASSIGN_RATE")));
                if (needMoney > (Double.parseDouble(queryBalanceResponse.getAvlBal().replaceAll(",", "")))) {
                    transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                    transMessage.setMessage("承接失败,原因如下：余额不足!");
                    return transMessage;
                }
            } else {
                transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                transMessage.setMessage("承接失败,原因如下：" + queryBalanceResponse.getRespDesc());
                return transMessage;
            }
        } catch (Exception e) {
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            transMessage.setMessage("承接失败,原因如下：余额查询失败!具体信息如下:" + e.getMessage());
            return transMessage;
        }
        /** 折价后的金额 */
        Double creditDealAmt = creditAssign.getSellMoney()
                * (1 - Double.parseDouble(ConfigUtil.getParameter("ASSIGN_RATE")));
        /** 手续费 */
        Double fee = creditAssign.getSellMoney() * Double.parseDouble(ConfigUtil.getParameter("ASSIGN_FEE"));
        CreditAssignRequest reqMsg = new CreditAssignRequest();
        reqMsg.setPartnerType(PartnerType.FUND);// 客户端目前定死为资金池模式
        reqMsg.setLeftPlanNum(creditAssign.getLeftPlanNum());// 剩余期数
        reqMsg.setRepaymentedMoney(creditAssign.getRepaymentedMoney());// 已还本金金额
        reqMsg.setSellCustId(creditAssign.getSellTrustAccountId());// 转让人客户号
        reqMsg.setCreditAmt(MoneyUtil.convertFenToYuan(creditAssign.getSellMoney()));// 债权转让转出的本金
        reqMsg.setCreditDealAmt(MoneyUtil.convertFenToYuan(InvestUtils.accuracy(creditDealAmt)));// 承接金额
        reqMsg.setFee(MoneyUtil.convertFenToYuan(fee.longValue()));// 扣款手续费
        reqMsg.setBuyCustId(passport.getTrustAccountId());// 承接人客户号
        reqMsg.setBuyUserId(passport.getUserId().toString());// 承接人id
        reqMsg.setOrdId(String.valueOf(transMessage.getAssignId()));// 订单号
        reqMsg.setOrdDate(DateTimeUtil.formatToStr(new Date(), DateTimeUtil.DATE_FORMAT_YYYYMMDD));// 订单日期

        List<BorrowerDetail> listBorrowerDetail = new ArrayList<BorrowerDetail>();
        BorrowerDetail borrowerDetail = new CreditAssignRequest().new BidDetail().new BorrowerDetail();
        borrowerDetail.setBorrowerCustId(borrowInfo.getBorrowUserTrustAccountId());
        borrowerDetail.setBorrowerCreditAmt(MoneyUtil.convertFenToYuan(creditAssign.getSellMoney()));
        borrowerDetail.setPrinAmt(MoneyUtil.convertFenToYuan(creditAssign.getRepaymentedMoney()));// 已还金额
        borrowerDetail.setProId(borrowInfo.getId().toString());
        listBorrowerDetail.add(borrowerDetail);

        Map<String, List<BidDetail>> mapBidDetails = new HashMap<String, List<BidDetail>>();
        List<BidDetail> listBidDetail = new ArrayList<BidDetail>();
        BidDetail bidDetail = new CreditAssignRequest().new BidDetail();
        bidDetail.setBidOrdId(investInfo.getId().toString());
        bidDetail
                .setBidOrdDate(DateTimeUtil.formatToStr(investInfo.getInvestTime(), DateTimeUtil.DATE_FORMAT_YYYYMMDD));
        bidDetail.setBidCreditAmt(MoneyUtil.convertFenToYuan(creditAssign.getSellMoney()));// BidDetails中的转让金额总和等于CreditAmt
        bidDetail.setBorrowerDetails(listBorrowerDetail);
        listBidDetail.add(bidDetail);
        mapBidDetails.put("BidDetails", listBidDetail);
        reqMsg.setBidDetails(mapBidDetails);

        List<DivDetail> listDivDetails = new ArrayList<DivDetail>();
        DivDetail divDetail = new CreditAssignRequest().new DivDetail();
        divDetail.setDivAcctId("MDT000001");
        divDetail.setDivAmt(MoneyUtil.convertFenToYuan(fee.longValue()));
        listDivDetails.add(divDetail);
        reqMsg.setDivDetails(listDivDetails);

        reqMsg.setPartnerTransType(PartnerTransType.CreditAssign);
        reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
        ResponseMessage response = (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(reqMsg);
        transMessage.setCode(response.getRespCode());
        transMessage.setMessage(response.getRespDesc());
        return transMessage;
    }

    /**
     * <pre>
     * 手机发送短信验证码以找回密码
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.SendSmsForFindPwd)
    public FindPwdMessage sendSmsForFindPwd(FindPwdMessage transMessage) {
        logger.info("SendSmsForFindPwd: " + ObjectHelper.toJson(transMessage));
        if (StringUtils.isEmpty(transMessage.getMobile())) {
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            transMessage.setMessage("参数为空");
            return transMessage;
        }
        Object sendTime = request.getSession().getAttribute("REGSMSTIME");// regSmsTime
        long timeInterval = 30l;
        long nowTime = Calendar.getInstance().getTimeInMillis();
        if (sendTime == null) {
            request.getSession().setAttribute("REGSMSTIME", nowTime);
        } else {
            long countDown = nowTime - Long.parseLong(String.valueOf(sendTime));
            if (countDown >= 1000 * timeInterval) {
                request.getSession().setAttribute("REGSMSTIME", nowTime);
            } else {
                transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                transMessage.setMessage((timeInterval - countDown / 1000) + "s后，才能再次发送短信验证码");
                return transMessage;
            }
        }
        ResponseMessage response = serviceFactory.getUserInfoService().sendSMSForValidMobile(null,
                transMessage.getMobile(), null, VerifyType.FOUNDLOGINPWD);
        if (response != null) {
            if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                transMessage.setMessage("短信验证码已发送,请注意查收");
            } else {
                transMessage.setCode(response.getRespCode());
                transMessage.setMessage(response.getRespDesc());
            }
        } else {
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            transMessage.setMessage("短信验证码已发送失败");
        }
        return null;
    }

    /**
     * <pre>
     * 修改密码
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.UpdateLoginPwd)
    public FindPwdMessage updateLoginPwd(FindPwdMessage transMessage) {
        logger.info("UpdateLoginPwd: " + ObjectHelper.toJson(transMessage));

        if (StringHelper.isEmpty(transMessage.getNewpassword())) {
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            transMessage.setMessage("请输入新密码");
            return transMessage;
        }
        if (StringHelper.isEmpty(transMessage.getCheckCode())) {
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            transMessage.setMessage("请输入验证码");
            return transMessage;
        }
        /**
         * 手机验证码验证
         */
        SendSMSRequest smsrequest = new SendSMSRequest();
        smsrequest.setMobile(transMessage.getMobile());
        smsrequest.setType(VerifyType.FOUNDLOGINPWD);
        smsrequest.setVerifyCode(transMessage.getCheckCode());
        smsrequest.setTransType(TransCodeConstants.MemberTransCode.MEMBER_VALID_MOBILE_AFFIRM);
        ResponseMessage response = serviceFactory.getProtFactory().remoteTrans(smsrequest);
        if (!response.getRespCode().equals(RespCodeConstants.CommonCode.TRANS_SUC)) {
            String wanneng = Configuration.getValue("sms.validate.code");// 万能验证码
            if (!wanneng.equals(transMessage.getCheckCode())) {// 后门短信验证码验证
                transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                transMessage.setMessage("验证码错误");
                return transMessage;
            }
        }
        UserUpdatePwdRequest userUpdatePwdRequest = new UserUpdatePwdRequest();
        userUpdatePwdRequest.setPassword(transMessage.getNewpassword());
        userUpdatePwdRequest.setUserName(transMessage.getMobile());
        userUpdatePwdRequest.setTransType(TransCodeConstants.MemberTransCode.MEMBER_UPDATE_PWD);
        response = serviceFactory.getProtFactory().remoteTrans(userUpdatePwdRequest);

        if (response != null) {
            if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                transMessage.setCode(RespCodeConstants.CommonCode.TRANS_SUC);
                transMessage.setMessage("修改密码成功");
            } else {
                transMessage.setCode(response.getRespCode());
                transMessage.setMessage(response.getRespDesc());
            }
        } else {
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            transMessage.setMessage("修改密码失败");
        }
        return transMessage;
    }

    /**
     * <pre>
     * 退出
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.LoginOut)
    public PrivateMessage loginOut(PrivateMessage transMessage) {
        logger.info("LoginOut: " + ObjectHelper.toJson(transMessage));
        return null;
    }

    /**
     * 资金明细
     * 
     * @param transMessage
     *            资金明细查询请求消息
     * @return 资金明细查询响应消息
     */
    @RemoteTransaction(transType = WapTransType.AccountLogQuery)
    public AccountLogMessage AccountLogQuery(AccountLogMessage transMessage) {
        logger.info("TradeQuery: " + ObjectHelper.toJson(transMessage));
        Passport passport = transMessage.getPassport();
        try {
            if (validToken(passport.getUserName(), transMessage.getPassport().getToken())) {

                TransType[] transType = null;
                if (transMessage.getTransTypes() != null) {
                    transType = new TransType[transMessage.getTransTypes().length];
                    for (int i = 0; i < transMessage.getTransTypes().length; i++) {
                        AccountTransType type = transMessage.getTransTypes()[i];
                        TransType ty = TransType.valueOf(type.name());
                        transType[i] = ty;
                    }
                }

                QueryResult<com.hengpeng.msls.port.client.vo.client.AccountLog> result = userService.findAccountDetail(
                        passport.getUserName(), transMessage.getBeginTransTime(), transMessage.getEndTransTime(),
                        transType, transMessage.getCurrentPage() == null ? 1 : transMessage.getCurrentPage(),
                        transMessage.getPageSize() == null ? 10 : transMessage.getPageSize());
                if (!CommUtil.isEmpty(result)) {
                    if (CommUtil.isSuccess(result)) {
                        List<com.hengpeng.msls.port.client.vo.client.AccountLog> accountLogs = result.getResults();
                        result.setCode(RespCodeConstants.CommonCode.TRANS_SUC);
                        result.setMessage(RespCodeConstants.CommonCode.TRANS_SUC_MSG);
                        com.hengpeng.msls.port.client.vo.client.AccountLog[] accountLog = new com.hengpeng.msls.port.client.vo.client.AccountLog[accountLogs
                                .size()];
                        transMessage.setAccountLogs(accountLogs.toArray(accountLog));
                        transMessage.setTotalCount(result.getTotalCount());
                    } else {
                        transMessage.setCode(result.getCode());
                        transMessage.setMessage(result.getMessage());
                    }
                } else {
                    transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                    transMessage.setMessage("查询返回空");
                }
            } else {
                transMessage.setCode(TRANSACTION_RESPONSE_CODE_4054);
                transMessage.setMessage(TRANSACTION_RESPONSE_MESSAGE_4054);
            }
        } catch (Exception e) {
            logger.error("查询资金明细异常", e);
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            transMessage.setMessage(RespCodeConstants.CommonCode.TRANS_FAIL_MSG);
        }

        return transMessage;
    }

    /**
     * 充值
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.Pay)
    public TransMessage pay(PayRequest transMessage) {
        logger.info("Pay: " + ObjectHelper.toJson(transMessage));
        PayRequestMsg reqMsg = new PayRequestMsg();
        reqMsg.setUserId(transMessage.getUserId());
        reqMsg.setTransAmt(transMessage.getMoney());
        reqMsg.setPartnerTransType(PartnerTransType.NetSave);
        reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
        reqMsg.setBgRetUrl(service_notify_url);
        reqMsg.setRetUrl(page_return_url);
        ResponseMessage response = (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(reqMsg);
        transMessage.setHtmlString(response.getOrderFormContent());
        return transMessage;
    }

    /**
     * <pre>
     * 用户提现
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.UserDraw)
    public UserDrawMessage userDraw(UserDrawMessage transMessage) {
        logger.info("UserDraw:" + ObjectHelper.toJson(transMessage));
        if (Validate.validateObjectsNullOrEmpty(transMessage.getMoney())) {
            transMessage.setMessage("提现请求参数错误,请联系客服!");
            transMessage.setCode(RespCodeConstants.CommonCode.DATA_NOT_VALIDATA);
            return transMessage;
        }
        CashRequestMsg reqMsg = new CashRequestMsg();
        reqMsg.setUserId(transMessage.getUserId());
        reqMsg.setTransAmt(transMessage.getMoney());
        reqMsg.setPartnerTransType(PartnerTransType.Cash);
        reqMsg.setBgRetUrl(service_notify_url);
        reqMsg.setRetUrl(page_return_url);
        reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
        ResponseMessage response = (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(reqMsg);
        transMessage.setHtmlString(response.getOrderFormContent());

        return transMessage;
    }

    @RemoteTransaction(transType = WapTransType.UserBankCard)
    public UserBankCardMessage userBankCard(UserBankCardMessage transMessage) {
        try {
            logger.info("BindingBankCard:" + ObjectHelper.toJson(transMessage));
            Passport passport = transMessage.getPassport();
            if (validToken(passport.getUserName(), transMessage.getPassport().getToken())) {
                List<UserBankCard> list = serviceFactory.getUserBankCardService().findBankCard(passport.getUserName(),
                        transMessage.getBankCardId(), transMessage.getIsPriority());
                transMessage.setUserBankCardlist(list);
            } else {
                transMessage.setCode(TRANSACTION_RESPONSE_CODE_4054);
                transMessage.setMessage(TRANSACTION_RESPONSE_MESSAGE_4054);
            }
            return transMessage;
        } catch (Exception e) {
            logger.error("银行卡管理异常", e);
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            return transMessage;
        }
    }

    @RemoteTransaction(transType = WapTransType.BindingBankCard)
    public BindingBankCardMessage bindingBankCard(BindingBankCardMessage transMessage) {
        try {
            logger.info("BindingBankCard:" + ObjectHelper.toJson(transMessage));
            Passport passport = transMessage.getPassport();
            if (validToken(passport.getUserName(), transMessage.getPassport().getToken())) {
                UserBankCard card = new UserBankCard();
                ResponseMessage response = null;
                switch (transMessage.getOrderType()) {
                case ADD:
                    card.setBankCardNo(transMessage.getBankCardNo());
                    card.setBankName(transMessage.getBankName());
                    card.setCity(transMessage.getCity());
                    card.setProvince(transMessage.getProvince());
                    card.setIsPriority(transMessage.getIsPriority());
                    card.setRealName(transMessage.getRealName());
                    card.setSubbranch(transMessage.getSubbranch());
                    card.setUserName(passport.getUserName());
                    card.setMobile(transMessage.getMobile());
                    card.setCreateTime(new Date());
                    response = serviceFactory.getUserBankCardService().saveUserBankCard(card);
                    break;
                case UPDATE:
                    card = serviceFactory.getProtFactory().getEntityById(transMessage.getBankCardId(),
                            UserBankCard.class);
                    if (card == null) {
                        transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                        transMessage.setMessage("银行卡不存在");
                        return transMessage;
                    }
                    card.setBankCardNo(transMessage.getBankCardNo());
                    card.setBankName(transMessage.getBankName());
                    card.setCity(transMessage.getCity());
                    card.setProvince(transMessage.getProvince());
                    card.setIsPriority(transMessage.getIsPriority());
                    card.setRealName(transMessage.getRealName());
                    card.setSubbranch(transMessage.getSubbranch());
                    card.setMobile(transMessage.getMobile());
                    response = serviceFactory.getUserBankCardService().updateUserBankCard(card);
                    break;
                case DELETE:
                    card = serviceFactory.getProtFactory().getEntityById(transMessage.getBankCardId(),
                            UserBankCard.class);
                    if (card == null) {
                        transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                        transMessage.setMessage("银行卡不存在");
                        return transMessage;
                    }
                    response = serviceFactory.getUserBankCardService().deleteUserBankCard(card);
                    break;
                case BINDING:
                    card = serviceFactory.getProtFactory().getEntityById(transMessage.getBankCardId(),
                            UserBankCard.class);
                    if (card == null) {
                        transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                        transMessage.setMessage("银行卡不存在");
                        return transMessage;
                    }
                    response = serviceFactory.getUserBankCardService().userBankCard(card);
                    break;
                default:
                    transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                    transMessage.setMessage("银行卡管理操作错误");
                    return transMessage;
                }
                if (response.getRespCode().equalsIgnoreCase(RespCodeConstants.CommonCode.TRANS_SUC)) {
                    transMessage.setCode(RespCodeConstants.CommonCode.TRANS_SUC);
                    transMessage.setMessage(response.getRespDesc());
                } else {
                    transMessage.setCode(response.getRespCode());
                    transMessage.setMessage(response.getRespDesc());
                }
            } else {
                transMessage.setCode(TRANSACTION_RESPONSE_CODE_4054);
                transMessage.setMessage(TRANSACTION_RESPONSE_MESSAGE_4054);
            }
            return transMessage;
        } catch (Exception e) {
            logger.error("银行卡管理异常", e);
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            return transMessage;
        }
    }

    /**
     * <pre>
     * 实名认证
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.Authentication)
    public MemberInfoMessage authentication(MemberInfoMessage transMessage) {
        logger.info("Authentication: " + ObjectHelper.toJson(transMessage));
        Passport passport = transMessage.getPassport();
        try {
            if (Validate.validateObjectsNullOrEmpty(transMessage.getRealName(), transMessage.getCardNumber())) {
                transMessage.setMessage("提现请求参数错误,请联系客服!");
                transMessage.setCode(RespCodeConstants.CommonCode.DATA_NOT_VALIDATA);
                return transMessage;
            }
            if (validToken(passport.getUserName(), transMessage.getPassport().getToken())) {
                if (CommUtil.validateObjectsNull(transMessage.getCardNumber(), transMessage.getRealName())) {
                    transMessage.setMessage("实名认证请求参数错误,请联系客服!");
                    transMessage.setCode(RespCodeConstants.CommonCode.DATA_NOT_VALIDATA);
                    return transMessage;
                }
                if (!IdCardUtils.validateCard(transMessage.getCardNumber())) {
                    transMessage.setMessage("身份证格式不正确!");
                    transMessage.setCode(RespCodeConstants.CommonCode.DATA_NOT_VALIDATA);
                    return transMessage;
                }
                RealNameAuthRequest request = new RealNameAuthRequest();
                request.setUserName(passport.getUserName());
                request.setRealName(transMessage.getRealName());
                request.setCardNumber(transMessage.getCardNumber());
                request.setTransType(TransCodeConstants.MemberTransCode.MEMBER_REALNAME_AUTH);
                UserInfoResponse response = (UserInfoResponse) portFactory.remoteTrans(request);
                // MemberInfo member = memberInfoUpdateRes.getMember();
                if (!CommUtil.isEmpty(response)) {
                    if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                        UserInfo userInfo = response.getUserInfo();
                        transMessage.setCode(RespCodeConstants.CommonCode.TRANS_SUC);
                        transMessage.setMessage("实名认证成功");
                        passport.setIdCode(userInfo.getCardNumber());
                        passport.setRealName(userInfo.getRealName());
                        passport.setIsRealNameCheck(userInfo.getIsRealNameCheck());
                    } else {
                        transMessage.setCode(response.getRespCode());
                        transMessage.setMessage(response.getRespDesc());
                    }
                } else {
                    transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                    transMessage.setMessage(RespCodeConstants.CommonCode.TRANS_FAIL_MSG);
                }
            } else {
                transMessage.setCode(TRANSACTION_RESPONSE_CODE_4054);
                transMessage.setMessage(TRANSACTION_RESPONSE_MESSAGE_4054);
            }
        } catch (Exception e) {
            logger.error("实名认证异常", e);
            transMessage.setMessage(RespCodeConstants.CommonCode.TRANS_FAIL_MSG);
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
        }
        return transMessage;
    }

    /**
     * <pre>
     * 修改密码
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.UpdatePassword)
    public LoginMessage UpdatePassword(LoginMessage transMessage) {
        logger.info("UpdatePassword: " + ObjectHelper.toJson(transMessage));
        try {
            if (Validate.validateObjectsNullOrEmpty(transMessage.getPassword(), transMessage.getNewpassword())) {
                transMessage.setMessage("提现请求参数错误,请联系客服!");
                transMessage.setCode(RespCodeConstants.CommonCode.DATA_NOT_VALIDATA);
                return transMessage;
            }
            Passport passport = transMessage.getPassport();
            if (validToken(passport.getUserName(), transMessage.getPassport().getToken())) {
                String encpassword = transMessage.getPassword();
                String decpassword = RSASignatureHelper.decryptByPrivateKey(encpassword, serverPrivateKey, "utf-8");
                String encNewPassword = transMessage.getNewpassword();
                String decNewPassword = RSASignatureHelper.decryptByPrivateKey(encNewPassword, serverPrivateKey,
                        "utf-8");
                UserUpdatePwdRequest request = new UserUpdatePwdRequest();
                request.setUserName(passport.getUserName());
                request.setOldPassword(decpassword);
                request.setPassword(decNewPassword);
                request.setTransType(TransCodeConstants.MemberTransCode.MEMBER_UPDATE_PWD);
                UserInfoResponse response = (UserInfoResponse) portFactory.remoteTrans(request);
                if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                    transMessage.setMessage("密码修改成功");
                    transMessage.setIsSuccess(true);
                    transMessage.setCode(RespCodeConstants.CommonCode.TRANS_SUC);
                } else {
                    transMessage.setIsSuccess(false);
                    transMessage.setMessage(response.getRespDesc());
                    transMessage.setCode(response.getRespCode());
                }
            } else {
                transMessage.setCode(TRANSACTION_RESPONSE_CODE_4054);
                transMessage.setMessage(TRANSACTION_RESPONSE_MESSAGE_4054);
            }
            return transMessage;
        } catch (Exception e) {
            logger.error("修改登录密码", e);
            transMessage.setMessage(RespCodeConstants.CommonCode.TRANS_FAIL_MSG);
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            return transMessage;
        }
    }

    /**
     * <pre>
     * 设置安全问题
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.SetQuestion)
    public UserSetProtectPwdMessage SetQuestion(UserSetProtectPwdMessage transMessage) {
        logger.info("SetQuestion: " + ObjectHelper.toJson(transMessage));
        try {
            if (Validate.validateObjectsNullOrEmpty(transMessage.getQuestionType(), transMessage.getAnswer())) {
                transMessage.setMessage("提现请求参数错误,请联系客服!");
                transMessage.setCode(RespCodeConstants.CommonCode.DATA_NOT_VALIDATA);
                return transMessage;
            }
            Passport passport = transMessage.getPassport();
            if (validToken(passport.getUserName(), transMessage.getPassport().getToken())) {
                UserSetProtectPwdRequest request = new UserSetProtectPwdRequest();
                request.setUserName(passport.getUserName());
                request.setQuestionType(transMessage.getQuestionType());
                request.setAnswer(transMessage.getAnswer());
                request.setTransType(TransCodeConstants.MemberTransCode.MEMBER_SET_PROTECT_PWD);
                UserInfoResponse response = (UserInfoResponse) portFactory.remoteTrans(request);
                if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                    UserInfo userInfo = response.getUserInfo();
                    transMessage.setMessage("设置安全问题成功");
                    transMessage.setCode(RespCodeConstants.CommonCode.TRANS_SUC);
                    passport.setIsQuestionCheck(userInfo.getIsQuestionCheck());
                    passport.setQuestionType(userInfo.getQuestionType());
                    passport.setAnswer(userInfo.getAnswer());
                } else {
                    transMessage.setMessage(response.getRespDesc());
                    transMessage.setCode(response.getRespCode());
                }
            } else {
                transMessage.setCode(TRANSACTION_RESPONSE_CODE_4054);
                transMessage.setMessage(TRANSACTION_RESPONSE_MESSAGE_4054);
            }
            return transMessage;
        } catch (Exception e) {
            logger.error("修改登录密码", e);
            transMessage.setMessage(RespCodeConstants.CommonCode.TRANS_FAIL_MSG);
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            return transMessage;
        }
    }

    /**
     * <pre>
     * 修改安全问题
     * </pre>
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.UpdateQuestion)
    public UserSetProtectPwdMessage UpdateQuestion(UserSetProtectPwdMessage transMessage) {
        logger.info("SetQuestion: " + ObjectHelper.toJson(transMessage));
        try {
            if (Validate.validateObjectsNullOrEmpty(transMessage.getOldQuestionType(), transMessage.getOldAnswer(),
                    transMessage.getQuestionType(), transMessage.getAnswer())) {
                transMessage.setMessage("提现请求参数错误,请联系客服!");
                transMessage.setCode(RespCodeConstants.CommonCode.DATA_NOT_VALIDATA);
                return transMessage;
            }
            Passport passport = transMessage.getPassport();
            if (validToken(passport.getUserName(), transMessage.getPassport().getToken())) {
                UserInfo userInfo = serviceFactory.getUserInfoService().getUserInfo(passport.getUserName());
                if (userInfo.getQuestionType() != transMessage.getOldQuestionType()) {
                    transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                    transMessage.setMessage("老问题错误");
                    return transMessage;
                }
                if (!transMessage.getOldAnswer().equals(userInfo.getAnswer())) {
                    transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                    transMessage.setMessage("老答案错误");
                    return transMessage;
                }
                UserSetProtectPwdRequest request = new UserSetProtectPwdRequest();
                request.setUserName(passport.getUserName());
                request.setQuestionType(transMessage.getQuestionType());
                request.setAnswer(transMessage.getAnswer());
                request.setTransType(TransCodeConstants.MemberTransCode.MEMBER_SET_PROTECT_PWD);
                UserInfoResponse response = (UserInfoResponse) portFactory.remoteTrans(request);
                if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                    userInfo = response.getUserInfo();
                    transMessage.setMessage("设置安全问题成功");
                    transMessage.setCode(RespCodeConstants.CommonCode.TRANS_SUC);
                    passport.setIsQuestionCheck(userInfo.getIsQuestionCheck());
                    passport.setQuestionType(userInfo.getQuestionType());
                    passport.setAnswer(userInfo.getAnswer());
                } else {
                    transMessage.setMessage(response.getRespDesc());
                    transMessage.setCode(response.getRespCode());
                }
            } else {
                transMessage.setCode(TRANSACTION_RESPONSE_CODE_4054);
                transMessage.setMessage(TRANSACTION_RESPONSE_MESSAGE_4054);
            }
            return transMessage;
        } catch (Exception e) {
            logger.error("修改登录密码", e);
            transMessage.setMessage(RespCodeConstants.CommonCode.TRANS_FAIL_MSG);
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            return transMessage;
        }
    }

    /**
     * 手机验证发送短信验证码
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.SendSMSForValidMobile)
    public LoginMessage sendSMSForValidMobile(LoginMessage transMessage) {
        logger.info("SendSMSForValidMobile:" + ObjectHelper.toJson(transMessage));
        try {
            if (CommUtil.validateObjectsNull(transMessage.getMobile())) {
                transMessage.setMessage("提现请求参数错误,请联系客服!");
                transMessage.setCode(RespCodeConstants.CommonCode.DATA_NOT_VALIDATA);
                return transMessage;
            }
            List<UserInfo> list = userService.getUserInfoByMone(transMessage.getMobile());

            String userName = "";
            /**
             * 校验投注卡号和绑定手机号码是否一致(手机号码就是登录用户名)
             */
            // 如果是注册且已经存在用户名，就返回错误码
            if (transMessage.getVerifyType() == LoginMessage.VerifyType.REGISTER) {
                if (null == list || list.size() != 0) {
                    transMessage.setMessage("手机号码已存在");
                    transMessage.setCode(RespCodeConstants.MemberCode.MOBILE_HAD_EXIST);
                    return transMessage;
                }
            } else if (transMessage.getVerifyType() == LoginMessage.VerifyType.VALIDMOBILE) {
                Passport passport = transMessage.getPassport();
                if (passport != null && validToken(passport.getUserName(), transMessage.getPassport().getToken())) {
                    userName = transMessage.getPassport().getUserName();
                } else {
                    transMessage.setCode(TRANSACTION_RESPONSE_CODE_4054);
                    transMessage.setMessage(TRANSACTION_RESPONSE_MESSAGE_4054);
                    return transMessage;
                }

            } else {
                if (null != list && list.size() != 0) {
                    userName = list.get(0).getUserName();
                } else {
                    transMessage.setMessage("用户不存在");
                    transMessage.setCode(RespCodeConstants.MemberCode.ACCOUNT_NOT_FOUND);
                    return transMessage;
                }
            }

            // 短信验证码发送
            ResponseMessage sendSms = userService.sendSMSForValidMobile(userName, transMessage.getMobile(), null,
                    VerifyType.valueOf(transMessage.getVerifyType().toString()));
            if (RespCodeConstants.CommonCode.TRANS_SUC.equals(sendSms.getRespCode())) {
                transMessage.setMessage("验证码发送成功,请注意查收！");
                transMessage.setCode(RespCodeConstants.CommonCode.TRANS_SUC);
                transMessage.setIsSuccess(true);
            } else {
                transMessage.setMessage(sendSms.getRespDesc());
                transMessage.setCode(sendSms.getRespCode());
            }
            return transMessage;
        } catch (Exception e) {
            logger.error("机验证发送短信验证码", e);
            transMessage.setMessage(RespCodeConstants.CommonCode.TRANS_FAIL_MSG);
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            return transMessage;
        }
    }

    /**
     * 手机号绑定
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.MobileBind)
    public LoginMessage MobileBind(LoginMessage transMessage) {
        logger.info("MobileBind:" + ObjectHelper.toJson(transMessage));
        try {
            if (CommUtil.validateObjectsNull(transMessage.getMobile(), transMessage.getVerifyCode())) {
                transMessage.setMessage("提现请求参数错误,请联系客服!");
                transMessage.setCode(RespCodeConstants.CommonCode.DATA_NOT_VALIDATA);
                return transMessage;
            }
            Passport passport = transMessage.getPassport();
            if (validToken(passport.getUserName(), transMessage.getPassport().getToken())) {
                // 验证码确认
                ResponseMessage response = userService.doValidMobile(passport.getUserName(), transMessage.getMobile(),
                        transMessage.getVerifyCode(), VerifyType.VALIDMOBILE);
                if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                    // 绑定手机号码
                    ResponseMessage message = userService.bingMobile(passport.getUserName(), transMessage.getMobile());
                    if (RespCodeConstants.CommonCode.TRANS_SUC.equals(message.getRespCode())) {
                        transMessage.setMessage("手机号绑定成功");
                        transMessage.setCode(RespCodeConstants.CommonCode.TRANS_SUC);
                        UserInfo userInfo = userService.getUserInfo(passport.getUserName());
                        passport.setIsMobileCheck(userInfo.getIsMobileCheck());
                        passport.setMobile(userInfo.getMobile());
                    } else {
                        transMessage.setMessage(message.getRespDesc());
                        transMessage.setCode(message.getRespCode());
                    }
                } else {
                    transMessage.setMessage(response.getRespDesc());
                    transMessage.setCode(response.getRespCode());
                }
            } else {
                transMessage.setCode(TRANSACTION_RESPONSE_CODE_4054);
                transMessage.setMessage(TRANSACTION_RESPONSE_MESSAGE_4054);
            }
            return transMessage;
        } catch (Exception e) {
            logger.error("手机号绑定", e);
            transMessage.setMessage(RespCodeConstants.CommonCode.TRANS_FAIL_MSG);
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            return transMessage;
        }
    }

    /**
     * 邮箱验证发送
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.sendValidEmail)
    public LoginMessage sendValidEmail(LoginMessage transMessage) {
        logger.info("sendValidEmail:" + ObjectHelper.toJson(transMessage));
        try {
            if (CommUtil.validateObjectsNull(transMessage.getEmail())) {
                transMessage.setMessage("提现请求参数错误,请联系客服!");
                transMessage.setCode(RespCodeConstants.CommonCode.DATA_NOT_VALIDATA);
                return transMessage;
            }
            Passport passport = transMessage.getPassport();
            if (validToken(passport.getUserName(), transMessage.getPassport().getToken())) {
                UserInfo userInfo = userService.getUserInfo(passport.getUserName());
                if (userInfo.getIsEmailCheck() == BoolValue.YES && transMessage.getEmail().equals(userInfo.getEmail())) {
                    transMessage.setMessage("新邮箱和老邮箱一样，无需修改");
                    transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                    return transMessage;
                }
                String domainName = SystemConfigUtil.getConfigValue("domainName");
                StringBuffer url = new StringBuffer();
                if (domainName.indexOf("http://") == -1) {
                    url.append("http://");
                }
                url.append(domainName);
                url.append("/memberCenter/doValidEmail.htm");
                ResponseMessage response = userService.sendMailForValid(transMessage.getEmail(),
                        passport.getUserName(), url.toString(), "");
                if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                    transMessage.setMessage("已发送验证邮件,请及时查收");
                    transMessage.setCode(RespCodeConstants.CommonCode.TRANS_SUC);
                } else {
                    transMessage.setMessage(response.getRespDesc());
                    transMessage.setCode(response.getRespCode());
                }
            } else {
                transMessage.setCode(TRANSACTION_RESPONSE_CODE_4054);
                transMessage.setMessage(TRANSACTION_RESPONSE_MESSAGE_4054);
            }
            return transMessage;
        } catch (Exception e) {
            logger.error("发送验证邮件", e);
            transMessage.setMessage(RespCodeConstants.CommonCode.TRANS_FAIL_MSG);
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            return transMessage;
        }
    }

    /**
     * 客户端版本
     * 
     * @param clientType
     *            客户端版本请求消息，需要提交客户端类型信息
     * @return
     */
    @RemoteTransaction(transType = WapTransType.ClientVersion)
    public ClientVersionInfo getClientVersion(ClientVersionInfo transMessage) {
        // 客户端类型
        ClientType clientType = transMessage.getClientType();
        String client_Version = "";
        String client_Summary = "";
        String client_IsForceUpdate = "";
        switch (clientType) {
        case ANDROID:
            client_Version = android_Client_Version;
            client_Summary = android_Client_Summary;
            client_IsForceUpdate = android_Client_IsForceUpdate;
            break;
        case IPHONE:
            client_Version = iphone_Client_Version;
            client_Summary = iphone_Client_Summary;
            client_IsForceUpdate = iphone_Client_IsForceUpdate;
            break;
        default:
            transMessage.setMessage("该客户端类型没有版本");
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            return transMessage;
        }

        // 版本号
        String version = SystemConfigUtil.getConfigValue(client_Version);

        // 升级说明
        String summary = SystemConfigUtil.getConfigValue(client_Summary);

        // 是否强制升级
        String isForceUpdate = SystemConfigUtil.getConfigValue(client_IsForceUpdate);

        if (CommUtil.validateObjectsNull(version, summary, isForceUpdate)) {
            transMessage.setMessage("升级参数错误 ");
            transMessage.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            return transMessage;
        }
        transMessage.setSummary(summary);
        transMessage.setVerName(version);
        transMessage.setForceUpdate(Boolean.valueOf(isForceUpdate));
        transMessage.setCode(RespCodeConstants.CommonCode.TRANS_SUC);
        transMessage.setMessage("成功");
        return transMessage;
    }

    /**
     * 我的红包信息列表
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.MyRedPacketQuery)
    public MyRedPacketQueryMessage myRedPacketQuery(MyRedPacketQueryMessage transMessage) {
        logger.info("MyRedPacketQuery: " + ObjectHelper.toJson(transMessage));
        int curPage = transMessage.getCurrentPage() != null ? transMessage.getCurrentPage() : 1;
        int psize = transMessage.getPageSize() != null ? transMessage.getPageSize() : 10;
        ServiceResult<List<RewardRedpacketVo>> sr = serviceFactory.getActivityService()
                .findRegRedpacketByStatus(Long.valueOf(transMessage.getUserId()), transMessage.getType(), curPage, psize);
/*        ServiceResult<List<RewardRedpacketVo>> sr = serviceFactory.getRedPacketService().queryMyVoList(
                transMessage.getUserId(), transMessage.getStatus(), curPage, psize);
*/        
        PageUtil pUtil = new PageUtil(psize, sr.getReturnListSize(), curPage);
        transMessage.setMyRedPacketList(sr.getReturnValue());
        transMessage.setCurrentPage(pUtil.getCurrentPage());
        transMessage.setTotalCount(pUtil.getTotalCount());
        transMessage.setPageSize(pUtil.getPageSize());
        return transMessage;
    }

    /**
     * 我的可用红包信息列表(用于投资)
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.MyCanuseRedPacketQuery)
    public MyRedPacketQueryMessage myCanuseRedPacketQuery(MyRedPacketQueryMessage transMessage) {
        logger.info("MyRedPacketQuery: " + ObjectHelper.toJson(transMessage));
        int curPage = transMessage.getCurrentPage() != null ? transMessage.getCurrentPage() : 1;
        int psize = transMessage.getPageSize() != null ? transMessage.getPageSize() : 10;
        ServiceResult<List<RewardRedpacketVo>> sr = serviceFactory.getActivityService().findRewardRedpacket(Long.valueOf(transMessage.getUserId()), RewardRedPacketStatus.CANUSE, curPage, psize);
        PageUtil pUtil = new PageUtil(psize, sr.getReturnListSize(), curPage);
        transMessage.setMyRedPacketList(sr.getReturnValue());
        transMessage.setCurrentPage(pUtil.getCurrentPage());
        transMessage.setTotalCount(pUtil.getTotalCount());
        transMessage.setPageSize(pUtil.getPageSize());
        return transMessage;
    }
    
    /**
     * 我的返利信息列表
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.MyRebateQuery)
    public MyRebateQueryMessage myRebateQuery(MyRebateQueryMessage transMessage) {
        logger.info("MyRebateQuery: " + ObjectHelper.toJson(transMessage));
        int curPage = transMessage.getCurrentPage() != null ? transMessage.getCurrentPage() : 1;
        int psize = transMessage.getPageSize() != null ? transMessage.getPageSize() : 10;
       /* ServiceResult<List<RewardRebate>> sr = serviceFactory.getRebateService().queryMyList(transMessage.getUserId(),
                curPage, psize);
        Long rewardRebateMoney = serviceFactory.getRebateService().countRewardRebate(transMessage.getUserId(), RewardRebateStatus.PAID);*/
        ServiceResult<List<RewardRebate>> sr = serviceFactory.getActivityService().findRewardRebate(transMessage.getUserId(), curPage, psize);;
        UserInfo userInfo = serviceFactory.getUserInfoService().getUserInfoById(transMessage.getUserId());
        String recommendCode = userInfo.getRecommendCode();
        Long inviteCount = serviceFactory.getActivityService().getFirstInviteCount(recommendCode);
        Long paidMoney = serviceFactory.getActivityService().getPaidMoney(userInfo.getId());
        Long unpayMoney = serviceFactory.getActivityService().getUnpayMoney(userInfo.getId());
        
        PageUtil pUtil = new PageUtil(psize, sr.getReturnListSize(), curPage);
        transMessage.setInviteCount(inviteCount.intValue());
        transMessage.setPaidMoney(paidMoney);
        transMessage.setUnpayMoney(unpayMoney);
        transMessage.setMyRebateList(sr.getReturnValue());
        transMessage.setCurrentPage(pUtil.getCurrentPage());
        transMessage.setTotalCount(pUtil.getTotalCount());
        transMessage.setPageSize(pUtil.getPageSize());
        return transMessage;
    }

    /**
     * 用户开户接口
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.Open)
    public OpenRequestMsg open(OpenRequestMsg transMessage) {

        com.hengpeng.itfinbase.message.partner.OpenRequestMsg reqMsg = new com.hengpeng.itfinbase.message.partner.OpenRequestMsg();
        reqMsg.setUserId(transMessage.getUserId());
        reqMsg.setCardNumber(transMessage.getCardNumber());
        reqMsg.setEmail(transMessage.getEmail());
        reqMsg.setMobile(transMessage.getMobile());
        reqMsg.setRealName(transMessage.getRealName());
        reqMsg.setMerPriv(transMessage.getUserId());
        reqMsg.setPartnerTransType(PartnerTransType.UserRegister);
        reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
        reqMsg.setBgRetUrl(service_notify_url);
        reqMsg.setRetUrl(page_return_url);
        ResponseMessage response = (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(reqMsg);
        String htmlString = response.getOrderFormContent();
        transMessage.setHtmlString(htmlString);
        return transMessage;

    }
    
    /**
     * 绑卡接口
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.UserBindCard)
    public BindCardRequest userBindCard(BindCardRequest transMessage) {
        
        com.hengpeng.itfinbase.message.partner.BindCardRequest reqMsg = new com.hengpeng.itfinbase.message.partner.BindCardRequest();
        
        UserInfo m = serviceFactory.getUserInfoService().getUserInfoById(transMessage.getUserId());
        reqMsg.setUserId(m.getId());
        reqMsg.setUsrCustId(m.getTrustAccountId());
        reqMsg.setPartnerTransType(PartnerTransType.UserBindCard);
        reqMsg.setBgRetUrl(service_notify_url);
        reqMsg.setRetUrl(page_return_url);
        reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
        ResponseMessage response = (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(reqMsg);
        String htmlString = response.getOrderFormContent();
        transMessage.setHtmlString(htmlString);
        return transMessage;
    }
    
    /**
     * 邀请好友
     * 
     * @param transMessage
     * @return
     */
    @RemoteTransaction(transType = WapTransType.MyInviteQuery)
    public MyInviteQueryMessage MyInviteQuery(MyInviteQueryMessage transMessage) {
        logger.info("MyInviteQueryMessage: " + ObjectHelper.toJson(transMessage));
        UserInfo userInfo = serviceFactory.getUserInfoService().getUserInfoById(transMessage.getUserId());
        String recommendCode = userInfo.getRecommendCode();
        Long firstCount = serviceFactory.getActivityService().getFirstInviteCount(recommendCode);
        Long secondCount = serviceFactory.getActivityService().getSecondInviteCount(recommendCode);
        Long thirdCount = serviceFactory.getActivityService().getThirdInviteCount(recommendCode);
        
        transMessage.setFirstCount(firstCount);
        transMessage.setSecondCount(secondCount);
        transMessage.setThirdCount(thirdCount);
        return transMessage;
    }
}